package com.itbour.web.action.tg;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.google.gson.Gson;
import com.itbour.com.page.Page;
import com.itbour.common.base.BaseAction;
import com.itbour.common.util.StringUtils;
import com.itbour.dto.com.UserInfoDto;
import com.itbour.dto.tg.MapPCInfoDto;
import com.itbour.dto.tg.MapPageInfoDto;
import com.itbour.dto.tg.MappingInfoDto;
import com.itbour.dto.tg.OutlineInfoDto;
import com.itbour.dto.tg.TgEgretInfoDto;
import com.itbour.dto.tg.TgEgretPCInfoDto;
import com.itbour.dto.tg.TgEgretPageInfoDto;
import com.itbour.dto.tg.TypeInfoDto;
import com.itbour.dto.tg.SizeInfoDto;
import com.itbour.service.tg.MappingService;
import com.opensymphony.xwork2.ActionContext;

/**
 * copyright Itbour team 2016
 * 
 * @author xc
 */

public class GetMappingWebAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	private MappingService mappingService;

	private String mapId;// 分页映射id
	private String ids;// 删除/更新用id
	private String order;// 显示顺序
	
	private String typeIds;// 模版类型id
	private String userId;

	private MappingInfoDto mappingInfo;

	private List<MappingInfoDto> mapInfoList = new ArrayList<MappingInfoDto>();
	private List<SizeInfoDto> sizeList = new ArrayList<SizeInfoDto>();
	
	private TgEgretInfoDto tgEgretInfo;// 编辑器加载用数据
	
	private String findPubFlg;// 检索条件
	private String findTmplName;// 检索条件
	private String findTmplType;// 检索条件
	HashMap<String, Object> mapResult = new HashMap<String, Object>();// 检索结果

	
	// 修改分页映射显示顺序
	public void updMappingOrder() throws Exception {
		if (StringUtils.isNotBlank(mapId)) {
			Map<String, Object> session = ActionContext.getContext().getSession();
	    	UserInfoDto user = (UserInfoDto)session.get("user");
	    	// update
	    	if(user!=null && user.getUser_id()!=null){
		    	Map<String, Object> param = new HashMap<String, Object>();
				param.put("order", order);
				param.put("map_id", mapId);
				param.put("update_by", user.getUser_id()+user.getUser_name());
				mappingService.updateMappingById(param);
	    	}
		}
		this.writeJSON("ok");
	}
	
	// 取消发布
	public void cancelPublish() throws Exception {
		if (StringUtils.isNotBlank(ids)) {
			Map<String, Object> session = ActionContext.getContext().getSession();
	    	UserInfoDto user = (UserInfoDto)session.get("user");
	    	if(user!=null && user.getUser_id()!=null){
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("publish", 0);
				param.put("ids", StringUtils.listToString2(StringUtils.stringToList2(ids)));
				param.put("update_by", user.getUser_id()+user.getUser_name());
				mappingService.updateMappingById(param);
	    	}
		}
		this.writeJSON("ok");
	}
	// 发布
	public void doPublish() throws Exception {
		// ids: ","连接
		if (StringUtils.isNotBlank(ids)) {
			Map<String, Object> session = ActionContext.getContext().getSession();
	    	UserInfoDto user = (UserInfoDto)session.get("user");
	    	if(user!=null && user.getUser_id()!=null){
	    		
	    		List<Long> listId = StringUtils.stringToList2(ids);
				// TODO check
				
		    	// update
	    		Map<String, Object> param = new HashMap<String, Object>();
				param.put("publish", 1);
				param.put("ids", StringUtils.listToString2(listId));
				param.put("update_by", user.getUser_id()+user.getUser_name());
				mappingService.updateMappingById(param);
	    	}
		}
		this.writeJSON("ok");
	}
	
	// 获取分页映射
	public String getMapping() throws Exception {

		HttpServletRequest request = ServletActionContext.getRequest();
		Map<String, Object> param = new HashMap<String, Object>();
		String id = request.getParameter("mapId");
		if (StringUtils.isNotEmpty(id)) {
			param.put("map_id", id);
		}
		param.put("del_flg", 0);

		mapInfoList = mappingService.selectMappingInfo(param);
		return SUCCESS;
	}
	
	// 获取分页映射列表
	public String getMappingInfoList() throws Exception {
		// 用户信息
		Map<String, Object> session = ActionContext.getContext().getSession();
    	UserInfoDto user = (UserInfoDto)session.get("user");
    	if(user!=null && user.getUser_id()!=null) {
    		HttpServletRequest request = ServletActionContext.getRequest();
    		String pageNumber = request.getParameter("page");
    		String pageSize = request.getParameter("rows");
    		Map<String, Object> param = new HashMap<String, Object>();
    		if (StringUtils.isNotBlank(findTmplType) && Long.valueOf(findTmplType)>0L) {
    			param.put("type_id", findTmplType);
    		}
    		if (StringUtils.isNotBlank(findPubFlg)) {
    			param.put("publish", findPubFlg);
    		}
    		if (StringUtils.isNotEmpty(findTmplName)) {
    			param.put("map_name", "%"+findTmplName+"%");
    		}

    		if(!user.isSuperUser()) {
    			//param.put("user_id", user.getUser_id());// 默认只检索自己的文档
    		}
    		
    		if (user.isAdmin()) {
    			// TODO
    		} else {
    			// 非管理员只能看到已发布的分页映射
    			param.put("publish", 1);
    		}
    		
    		Page page = mappingService.pageQuery(param, Integer.parseInt(pageNumber),
    				Integer.parseInt(pageSize));
    		HashMap<String, Object> resMap = new HashMap<String, Object>();
    		resMap.put("total", page.getTotalCount());
    		resMap.put("rows", page.getResult());
    		//writeJSON(resMap);
    		mapResult = resMap;
    	} else {
    		mapResult.clear();
    	}

		return SUCCESS;
	}
	
	// 删除分页映射
	public void deleteMapping() throws Exception {
		Map<String, Object> session = ActionContext.getContext().getSession();
    	UserInfoDto user = (UserInfoDto)session.get("user");
    	if(user!=null && user.getUser_id()!=null) {
    		Map<String, Object> param = new HashMap<String, Object>();
    		param.put("mapIds", StringUtils.listToString2(StringUtils.stringToList2(ids)));
			param.put("update_by", user.getUser_id()+user.getUser_name());
			mappingService.deleteMappingInfo(param);
			mappingService.deleteMapPageInfo(param);
			mappingService.deleteMapPCInfo(param);
    		this.writeJSON("ok");
    	} else {
    		this.writeJSON("ng");
    	}
	}

	// 新规分页映射
	public void addMapping() throws Exception {
		if (mappingInfo != null) {
			Map<String, Object> session = ActionContext.getContext().getSession();
	    	UserInfoDto user = (UserInfoDto)session.get("user");
	    	if (user != null) {
	    		mappingInfo.setUpdate_by(user.getUser_name());
	    		mappingInfo.setUser_id(user.getUser_id());
	    		mappingInfo.setUser_type(user.getUser_type());
	    	}
	    	
	    	mappingService.addMappingInfo(mappingInfo);
		}
		this.writeJSON("ok");
	}
	
	// 更新分页映射信息(编辑器用)
	public void updMapping() throws Exception {
		HashMap<String, Object> resMap = new HashMap<String, Object>();
		
		Map<String, Object> session = ActionContext.getContext().getSession();
    	UserInfoDto user = (UserInfoDto)session.get("user");
    	if (user != null) {
    		
    		HttpServletRequest request = ServletActionContext.getRequest();
    		String paramId = request.getParameter("id");
    		String paramSizeId = request.getParameter("sizeId");// 提纲id
    		String paramTgId = request.getParameter("tgId");// 提纲id
    		String paramName = request.getParameter("name");
    		String pJmData = request.getParameter("jmData");
    		String pEgretData = request.getParameter("egretData");
    		String ver = request.getParameter("ver");// 版本号，201610281602
    		
    		Gson gson = new Gson();
    		TgEgretInfoDto egretInfo = gson.fromJson(pEgretData, TgEgretInfoDto.class);
    		
    		if(egretInfo!=null){
    			Long retMapId = null;
    			// id不为空:更新
        		if (StringUtils.isNotBlank(paramId)) {
    				
        			// 非超级用户需要check
    				if(!user.isSuperUser()){
    					// user_id, tg_id关联check
    					Map<String, Object> chkParam = new HashMap<String, Object>();
    					chkParam.put("map_id", Long.valueOf(paramId.trim()));
    					chkParam.put("user_id", user.getUser_id());
    					chkParam.put("del_flg", 0);
    					List<MappingInfoDto> chkList = mappingService.selectMappingInfo(chkParam);
    					if (chkList == null || chkList.size() == 0) {
    						resMap.put("status", "ng");
    			      		resMap.put("msg", "本文档禁止修改！");
    			      		this.writeJSON(resMap);
    						return;
    					}
    				}
    				
    				// 更新
    				Map<String, Object> param = new HashMap<String, Object>();
    				param.put("map_id", Long.valueOf(paramId.trim()));
    				param.put("map_name", paramName);
    				param.put("size_id", Long.valueOf(paramSizeId));// 尺寸id
    				param.put("ver", Integer.valueOf(ver));// 版本号，201610281602
    				param.put("data", pJmData);
    				param.put("update_by", user.getUser_id().toString());
    				mappingService.updateMappingById(param);
    				
    				// TODO
    				// 先逻辑删除Page/PC信息
    				mappingService.deleteMapPageInfo(param);
    				mappingService.deleteMapPCInfo(param);
    				
    				// 返回值
    				retMapId = Long.valueOf(paramId.trim());
    	      		
    			// id为空:新规
    			} else {
    				if (StringUtils.isNotBlank(paramTgId) && Long.valueOf(paramTgId)>0L) {
    					// 检索提纲
    					Map<String, Object> param = new HashMap<String, Object>();
    					param.put("tg_id", paramTgId);
    					param.put("del_flg", 0);
    					List<OutlineInfoDto> outlineInfoList = mappingService.selectOutlineInfo(param);
    					
    					if(outlineInfoList!=null && outlineInfoList.size()>0){
    						// 新规分页Doc
    						MappingInfoDto info = new MappingInfoDto();
    						info.setData(pJmData);// 脑图数据
    						info.setMap_name(paramName);
    						info.setTg_id(Long.valueOf(paramTgId));// 提纲id
    						info.setSize_id(Long.valueOf(paramSizeId));// 尺寸id
    						info.setType_id(outlineInfoList.get(0).getType_id());// 分类id
    						info.setVer(Integer.valueOf(ver));// 版本号，201610281602
    						info.setPublish(0);// 默认制作中
    						info.setUser_id(user.getUser_id());
    						info.setUser_type(user.getUser_type());
    						info.setUpdate_by(user.getUser_id().toString());
    						Long newMapId = mappingService.addMappingInfo(info);
    						
    						// 返回值
    						retMapId = newMapId;
    						
    					} else {
    						resMap.put("msg", "提纲ID错误！");
    			      		resMap.put("status", "ng");
    			    		this.writeJSON(resMap);
    			    		return;
    					}
    		      		
    				} else {
    		      		resMap.put("msg", "提纲ID未指定！");
    		      		resMap.put("status", "ng");
    		    		this.writeJSON(resMap);
    		    		return;
    				}
    			}
        		
        		// 新建page/pc信息
        		// 循环page信息
				for(int i=0; i<egretInfo.getPagesData().size(); i++) {
					TgEgretPageInfoDto pageInfo = egretInfo.getPagesData().get(i);
					
					// 新规分页page
					MapPageInfoDto mapPageDto = new MapPageInfoDto();
					mapPageDto.setMap_id(retMapId);
					mapPageDto.setPage_index(Integer.valueOf(pageInfo.getPage_index()));
					mapPageDto.setHash_tag(pageInfo.getHash_tag());
					mapPageDto.setData(pageInfo.getData());
					mapPageDto.setBackup_flg(Integer.valueOf(pageInfo.getBackup_flg()));
					mapPageDto.setThumb(null);
					mapPageDto.setUpdate_by(user.getUser_id().toString());
					Long newPageId = mappingService.addMapPageInfo(mapPageDto);
					
					// 循环pc信息
					for(int j=0; j<pageInfo.getPcData().size(); j++) {
						TgEgretPCInfoDto pcInfo = pageInfo.getPcData().get(j);
						
						// 新规分页pc
						MapPCInfoDto mapPcDto = new MapPCInfoDto();
						mapPcDto.setPage_id(newPageId);
						mapPcDto.setMap_id(retMapId);
						mapPcDto.setPc_index(Integer.valueOf(pcInfo.getPc_index()));
						mapPcDto.setBackup_flg(Integer.valueOf(pcInfo.getBackup_flg()));
						mapPcDto.setHash_tag(pcInfo.getHash_tag());
						mapPcDto.setData(pcInfo.getData());
						mapPcDto.setReplaces(pcInfo.getReplaces());
						mapPcDto.setThumb_s(null);
						mapPcDto.setUpdate_by(user.getUser_id().toString());
						Long newPcId = mappingService.addMapPCInfo(mapPcDto);
					}
				}
        		
        		resMap.put("mapId",retMapId);
	      		resMap.put("status", "ok");
	    		this.writeJSON(resMap);
	    		return;
    			
    		} else {
    			resMap.put("msg", "分页数据错误！");
    			resMap.put("status", "ng");
    			this.writeJSON(resMap);
    			return;
    		}
    		
    	} else {
      		resMap.put("msg", "非法用户！");
      		resMap.put("status", "ng");
    		this.writeJSON(resMap);
    		return;
    	}
	}
	
	// 获取分页映射数据(编辑器用)
	public String getMapping2() throws Exception {
		
		if(tgEgretInfo==null) {
			tgEgretInfo = new TgEgretInfoDto();
		}

		HttpServletRequest request = ServletActionContext.getRequest();
		String id = request.getParameter("mapId");
		if (StringUtils.isNotEmpty(id)) {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("map_id", id);
			param.put("del_flg", 0);
			// 获取doc信息
			List<MappingInfoDto> docLst = mappingService.selectMappingInfo(param);
			if(docLst!=null && docLst.size()>0) {
				MappingInfoDto dbDocInfo = docLst.get(0);
				
				// 获取page信息
				List<MapPageInfoDto> pageLst = mappingService.selectMapPageInfo(param);
				if(pageLst!=null && pageLst.size()>0) {
					
					List<TgEgretPageInfoDto> retPagesData = new ArrayList<TgEgretPageInfoDto>();
					for(int i=0; i<pageLst.size(); i++) {
						MapPageInfoDto dbPageInfo = pageLst.get(i);
						
						TgEgretPageInfoDto pageData = new TgEgretPageInfoDto();
						pageData.setData(dbPageInfo.getData());
						pageData.setPage_index(dbPageInfo.getPage_index().toString());
						pageData.setPage_id(dbPageInfo.getPage_id().toString());
						
						// 获取pc信息
						Map<String, Object> param2 = new HashMap<String, Object>();
						param2.put("map_id", id);
						param2.put("page_id", dbPageInfo.getPage_id());
						param2.put("del_flg", 0);
						List<MapPCInfoDto> pcLst = mappingService.selectMapPCInfo(param2);
						
						List<TgEgretPCInfoDto> retPcData = new ArrayList<TgEgretPCInfoDto>();
						for(int j=0; j<pcLst.size(); j++) {
							MapPCInfoDto dbPcInfo = pcLst.get(0);
							
							TgEgretPCInfoDto pcData = new TgEgretPCInfoDto();
							pcData.setData(dbPcInfo.getData());
							pcData.setPc_index(dbPcInfo.getPc_index().toString());
							pcData.setPc_id(dbPcInfo.getPc_id().toString());
							
							// add pc data
							retPcData.add(pcData);
						}
						
						// set return pc data
						pageData.setPcData(retPcData);
						
						// add page data
						retPagesData.add(pageData);
					}
					
					// set return page data
					tgEgretInfo.setPagesData(retPagesData);
					tgEgretInfo.setName(dbDocInfo.getMap_name());
				}
			}
		}
		
		return SUCCESS;
	}
	
	// 获取尺寸信息列表
	public String getSizeInfoList() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String flg = request.getParameter("flg");// 0:横屏; 1:竖屏
		Map<String, Object> param = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(flg)){
			param.put("portrait", flg);
		}else{
			param.put("portrait", 1);
		}
		sizeList = mappingService.selectSizeInfoList(param);
		return SUCCESS;
	}


	public MappingService getMappingService() {
		return mappingService;
	}

	public void setMappingService(MappingService mappingService) {
		this.mappingService = mappingService;
	}

	public String getMapId() {
		return mapId;
	}

	public void setMapId(String mapId) {
		this.mapId = mapId;
	}

	public MappingInfoDto getMappingInfo() {
		return mappingInfo;
	}

	public void setMappingInfo(MappingInfoDto mappingInfo) {
		this.mappingInfo = mappingInfo;
	}

	public List<MappingInfoDto> getMapInfoList() {
		return mapInfoList;
	}

	public void setMapInfoList(List<MappingInfoDto> mapInfoList) {
		this.mapInfoList = mapInfoList;
	}

	public List<SizeInfoDto> getSizeList() {
		return sizeList;
	}

	public void setSizeList(List<SizeInfoDto> sizeList) {
		this.sizeList = sizeList;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getFindTmplType() {
		return findTmplType;
	}

	public void setFindTmplType(String findTmplType) {
		this.findTmplType = findTmplType;
	}

	public String getFindPubFlg() {
		return findPubFlg;
	}

	public void setFindPubFlg(String findPubFlg) {
		this.findPubFlg = findPubFlg;
	}

	public String getFindTmplName() {
		return findTmplName;
	}

	public void setFindTmplName(String findTmplName) {
		this.findTmplName = findTmplName;
	}

	public HashMap<String, Object> getMapResult() {
		return mapResult;
	}

	public void setMapResult(HashMap<String, Object> mapResult) {
		this.mapResult = mapResult;
	}

	public String getTypeIds() {
		return typeIds;
	}

	public void setTypeIds(String typeIds) {
		this.typeIds = typeIds;
	}

	public String getOrder() {
		return order;
	}

	public void setOrder(String order) {
		this.order = order;
	}

	public TgEgretInfoDto getTgEgretInfo() {
		return tgEgretInfo;
	}

	public void setTgEgretInfo(TgEgretInfoDto tgEgretInfo) {
		this.tgEgretInfo = tgEgretInfo;
	}

}
